import { useState, useRef } from 'react';
import { request, useModel } from '@umijs/max';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Row, Col, Select, message, Input, Button, Space, Popconfirm, Form, Modal, DatePicker, InputNumber, Upload } from 'antd';
import type { GetProp, UploadProps } from 'antd';
import { PlusOutlined, DeleteOutlined, EditOutlined, UploadOutlined } from '@ant-design/icons';
import dayjs from 'dayjs'
const { TextArea } = Input;

type TaskItem = {
  id: number,
  amount: string,
  name: string,
  patentType: string,
  patentField: string,
  requestTime: string,
  gradeType: string,
  contacts: string,
  contactsPhone: string,
  writingRequirements: string,
  fileUserlist: []
};

export default () => {
  const actionRef = useRef<ActionType>();
  const { initialState } = useModel("@@initialState");
  // @ts-ignore
  const { dictData } = initialState;

  //新增转让相关
  const [form] = Form.useForm();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const onAdd = () => {
    form.resetFields();
    setIsModalOpen(true);
  }
  const handleOk = () => {
    form.validateFields()
      .then(async (values) => {
        values.requestTime = dayjs(values.requestTime).format('YYYY-MM-DD');
        await request('/system/taskApi', { method: values.id ? 'PUT' : 'POST', data: values });
        setIsModalOpen(false);
        message.success(values.id ? '编辑成功' : '新增成功');
        actionRef.current?.reload();
      })
      .catch(() => {})
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  //编辑转让相关
  const onEdit = async (item: TaskItem) => {
    const { id} = item;
    const { data } = await request('/system/taskApi/' + id);
    const { amount, name, patentType, patentField, requestTime, writingRequirements, contacts, contactsPhone, gradeType, fileUserlist }: TaskItem = data;
    form.setFieldsValue({
      id,
      amount, name, patentType, patentField,
      requestTime: dayjs(requestTime), gradeType,
      contacts, contactsPhone,
      writingRequirements, fileUserlist
    });
    setIsModalOpen(true);
  }

  //删除转让相关
  const onDelete = async (item: TaskItem) => {
    const {id} = item;
    await request('/system/taskApi/' + id, { method: 'DELETE' });
    message.success('删除成功');
    actionRef.current?.reload();
  }

  //上传文件
  type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];
  const props: UploadProps = {
    name: 'file',
    accept: ".rar,.zip,.doc,.docx,.pdf,.jpg,.png",
    action: 'http://47.120.71.81/prod-api/common/uploadFileOss',
    headers: {
      Authorization: localStorage.getItem('token') || "",
    },
    onRemove(file) {
      console.log(file)
    },
    beforeUpload(file: FileType) {
      const isLt10M = file.size / 1024 / 1024 <= 10;
      if (!isLt10M) {
        message.error("上传文件大小不得超过10M");
        // this.onRemove(file);
        return false;
      }
    },
    onChange({ file }) {
      const { status, response } = file;
      if (status === 'done') {
        const {msg: url} = response;
        console.log(url)
        message.success(`文件上传成功`);
      } else if (status === 'error') {
        message.error('文件上传失败');
      }
    },
    progress: {
      strokeColor: {
        '0%': '#108ee9',
        '100%': '#87d068',
      },
      strokeWidth: 3,
      format: (percent) => percent && `${parseFloat(percent.toFixed(2))}%`,
    },
  };
  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  };


  const columns: ProColumns<TaskItem>[] = [
    {
      title: '发明名称',
      dataIndex: 'name',
      ellipsis: true,
    },
    {
      width: 80,
      title: '专利类型',
      dataIndex: 'patentType',
      valueType: 'select',
      fieldProps: {
        options: dictData['专利类型']
      },
    },
    {
      width: 100,
      title: '代理师等级',
      dataIndex: 'gradeType',
      valueType: 'select',
      fieldProps: {
        options: dictData['代理师等级']
      },
    },
    {
      width: 100,
      title: '要求时限',
      hideInSearch: true,
      dataIndex: 'requestTime',
    },
    {
      title: '撰写要求',
      dataIndex: 'writingRequirements',
      ellipsis: true,      //是否自动缩略
      copyable: false,      //是否支持复制
      hideInSearch: true,  //在查询表单中不展示此项
    },
    {
      width: 100,
      title: '金额',
      dataIndex: 'amount',
      valueType: 'money',
    },
    {
      width: 90,
      title: '操作',
      key: 'action',
      hideInSearch: true,
      render: (_, record) => (
        <Space size="middle">
          <Button
            onClick={() => onEdit(record)}
            icon={<EditOutlined />}
            type="primary"
            size="small">
          </Button>
          <Popconfirm
            title="删除提示"
            description="确定删除该数据吗?"
            onConfirm={() => onDelete(record)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              icon={<DeleteOutlined />}
              type="primary"
              size="small"
              danger>
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<TaskItem>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        request={async (params) => {
          const {current, pageSize} = params;
          const params_ = {
            ...params,
            pageSize,
            pageNum: current,
          }
          delete params_.current;
          const result =  await request('/system/taskApi/listUser', { method: 'GET', params: params_ });
          return {
            data: result?.rows,
            success: result?.code === 200,
            total: result?.total,
          }
        }}
        columnsState={{
          persistenceKey: 'taskManagement-table',
          persistenceType: 'localStorage',
          defaultValue: {
            option: { fixed: 'right', disable: true },
          },
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
          span: 6,
        }}
        options={{
          //菜单栏 options 配置
          fullScreen: true,
          density: true,
          setting: {
            draggable: true,
            checkable: true,
            checkedReset: true,
            listsHeight: 400,
          },
        }}
        pagination={{
          pageSize: 5,
          onChange: (page) => console.log(page),
        }}
        dateFormatter={false}
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={onAdd}
            type="primary"
          >
            新建
          </Button>
        ]}
      />
      <Modal
        title="新增任务"
        width={800}
        maskClosable={false}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}>
        <Form
          name="basic"
          form={form}
          labelCol={{
            span: 6,
          }}
          wrapperCol={{
            span: 18,
          }}
          initialValues={{
            id: "",
            amount: "",
            name: "",
            patentType: "",
            patentField: "",
            requestTime: "",
            gradeType: "",
            contacts: "",
            contactsPhone: "",
            writingRequirements: "",
            fileUserlist: [],
          }}
          autoComplete="off"
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="ID"
                name="id"
                hidden
              >
                <Input />
              </Form.Item>
              <Form.Item
                label="金额"
                name="amount"
              >
                <InputNumber
                  prefix="￥"
                  style={{width: '100%'}}
                  controls={true} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="发明名称"
                name="name"
                rules={[
                  {
                    required: true,
                    message: '请输入发明名称!',
                  },
                ]}
              >
                <Input maxLength={30} showCount={true} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="专利类型"
                name="patentType"
                rules={[
                  {
                    required: true,
                    message: '请输入专利类型!',
                  },
                ]}
              >
                <Select options={dictData['专利类型']} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="专利领域"
                name="patentField"
                rules={[
                  {
                    required: true,
                    message: '请输入专利领域!',
                  },
                ]}
              >
                <Select options={dictData['专利领域']} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="要求时限"
                name="requestTime"
              >
                <DatePicker style={{width: '100%'}} format='YYYY-MM-DD' />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="代理师"
                name="gradeType"
                rules={[
                  {
                    required: true,
                    message: '请输入代理师!',
                  },
                ]}
              >
                <Select options={dictData['代理师等级']} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="联系人"
                name="contacts"
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="联系人手机号"
                name="contactsPhone"
                rules={[
                  {
                    pattern: /^1(3[0-9]|4[01456879]|5[0-3,5-9]|6[2567]|7[0-8]|8[0-9]|9[0-3,5-9])\d{8}$/,
                    message: '请输入正确的手机号'
                  }
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item
                label="撰写要求"
                name="writingRequirements"
                labelCol={{span: 3}}
                wrapperCol={{span: 21}}
              >
                <TextArea maxLength={300} showCount={true} rows={4} />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item
                label="上传文件"
                name="fileUserlist"
                labelCol={{span: 3}}
                wrapperCol={{span: 21}}
                valuePropName="fileList"
                getValueFromEvent={normFile}
                extra="上传文件大小不得超过10M"
              >
                <Upload {...props}>
                  <Button icon={<UploadOutlined />}>点击上传</Button>
                </Upload>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </PageContainer>
  );
};
